package com.tyqx.biz.controller.eth.scheduler;


import com.tyqx.bean.model.EthPoolInfo;
import com.tyqx.biz.controller.Constants;
import com.tyqx.biz.controller.JsoupUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.tyqx.service.EthPoolInfoService;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class SchedulerEthInfo {

    private static final Logger logger = LoggerFactory.getLogger(SchedulerEthInfo.class);


    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private EthPoolInfoService ethPoolInfoService;

    @Autowired
    private Constants constants;

    @Resource
    private JsoupUtil jsoupUtil;

    @Async
    //表示每隔秒
    @Scheduled(fixedRate = 60 * 1000 * 1)
    //@Scheduled(fixedDelay = 1000 * 60 * 3)
    public void testTasks() throws Exception {
        logger.debug("定时器开始执行："+dateFormat.format(new Date())+"\n");
        logger.debug("webSocketDebuggerUrl:"+constants.webSocketDebuggerUrl);
        try{
            String viewBlockUrl = "https://cn.etherscan.com/blocks";

            String homeUrl = "https://cn.etherscan.com/";

            List<EthPoolInfo> ethPoolInfoList = jsoupUtil.getEthPoolInfoList(viewBlockUrl,homeUrl);

            logger.debug("走到这里了");
            if(ethPoolInfoList.size()>0){
                List<EthPoolInfo> ethPoolInfos = new ArrayList<>();
                for (int i=0;i<ethPoolInfoList.size();i++){
                    Long blockNum = ethPoolInfoList.get(i).getBlock();
                    if(ethPoolInfoService.selectEthInfoByBlockNum(blockNum)>0){

                    }else{
                        ethPoolInfos.add(ethPoolInfoList.get(i));
                    }
                }
                if(ethPoolInfos.size()>0){
                    Integer flag = ethPoolInfoService.insertBatch(ethPoolInfos);
                    if(flag>0){
                        logger.debug("获取eth最新数据成功");
                    }else{
                        logger.error("获取eth最新数据失败");
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        logger.debug("定时器结束执行："+dateFormat.format(new Date())+"\n");
    }
}